home *** CD-ROM | disk | FTP | other *** search
/ PC Format (PL) 2013 August / PC_Format_082013.iso / pene wersje / website x5 home 10 / wsx5_home.exe / {app} / Res / x5engine.php < prev   
PHP Script  |  2013-05-29  |  55KB  |  1,486 lines

  1. <?php
  2.  
  3. /**
  4.  * This file contains all the classes used by the PHP code created by WebSite X5
  5.  *
  6.  * @category  X5engine
  7.  * @package   X5engine
  8.  * @copyright 2013 - Incomedia Srl
  9.  * @license   Copyright by Incomedia Srl http://incomedia.eu
  10.  * @version   WebSite X5 HOME 10.0.0
  11.  * @link      http://websitex5.com
  12.  */
  13.  
  14. @session_start();
  15.  
  16. $imSettings = Array();
  17. $l10n = Array();
  18. $phpError = false;
  19. $ImMailer = new ImSendEmail();
  20.  
  21. @include_once "imemail.inc.php";        // Email class - Static
  22. @include_once "x5settings.php";            // Basic settings - Dynamically created by WebSite X5
  23. @include_once "access.inc.php";            // Private area data - Dynamically created by WebSite X5
  24. @include_once "l10n.php";                // Localizations - Dynamically created by WebSite X5
  25. @include_once "search.inc.php" ;        // Search engine data - Dynamically created by WebSite X5
  26.  
  27.  
  28.  
  29.  
  30. /**
  31.  * Captcha handling class
  32.  * @access public
  33.  */
  34. class imCaptcha {
  35.  
  36.     /**
  37.      * Show the captcha chars
  38.      */
  39.     function show($sCode)
  40.     {
  41.         global $oNameList;
  42.         global $oCharList;
  43.  
  44.         $text = "<!DOCTYPE HTML>
  45.             <html>
  46.           <head>
  47.           <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">
  48.           <meta http-equiv=\"pragma\" content=\"no-cache\">
  49.           <meta http-equiv=\"cache-control\" content=\"no-cache, must-revalidate\">
  50.           <meta http-equiv=\"expires\" content=\"0\">
  51.           <meta http-equiv=\"last-modified\" content=\"\">
  52.           </head>
  53.           <body style=\"margin: 0; padding: 0; border-collapse: collapse;\">";
  54.  
  55.         for ($i=0; $i<strlen($sCode); $i++)
  56.             $text .= "<img style=\"margin:0; padding:0; border: 0; border-collapse: collapse; width: 24px; height: 24px; position: absolute; top: 0; left: " . (24 * $i) . "px;\" src=\"imcpa_".$oNameList[substr($sCode, $i, 1)].".gif\" width=\"24\" height=\"24\">";
  57.  
  58.         $text .= "</body></html>";
  59.  
  60.         return $text;
  61.     }
  62.  
  63.     /**
  64.      * Check the sent data
  65.      * @param sCode The correct code (string)
  66.      * @param dans The user's answer (string)
  67.      */
  68.     function check($sCode, $ans)
  69.     {
  70.         global $oCharList;
  71.         if ($ans == "")
  72.             return '-1';
  73.         for ($i=0; $i<strlen($sCode); $i++)
  74.           if ($oCharList[substr(strtoupper($sCode), $i, 1)] != substr(strtoupper($ans), $i, 1))
  75.             return '-1';
  76.         return '0';
  77.     }
  78. }
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90. /**
  91.  * Private area
  92.  * @access public
  93.  */
  94. class imPrivateArea
  95. {
  96.  
  97.     var $session_uname;
  98.     var $session_uid;
  99.     var $session_page;
  100.     var $cookie_name;
  101.  
  102.     // PHP 5
  103.     function __contruct()
  104.     {
  105.         $this->session_uname = "im_access_uname";
  106.         $this->session_real_name = "im_access_real_name";
  107.         $this->session_page = "im_access_request_page";
  108.         $this->session_uid = "im_access_uid";
  109.         $this->cookie_name = "im_access_cookie_uid";
  110.     }
  111.  
  112.     // PHP 4
  113.     function imPrivateArea()
  114.     {
  115.         $this->session_uname = "im_access_uname";
  116.         $this->session_real_name = "im_access_real_name";
  117.         $this->session_page = "im_access_request_page";
  118.         $this->session_uid = "im_access_uid";
  119.         $this->cookie_name = "im_access_cookie_uid";
  120.     }
  121.  
  122.     /**
  123.      * Encode the string
  124.      * @param  string $string The string to encode
  125.      * @param  $key The encryption key
  126.      * @return string    The encoded string
  127.      */
  128.     function _encode($s, $k)
  129.     {
  130.         $r = array();
  131.         for($i = 0; $i < strlen($s); $i++)
  132.             $r[] = ord($s[$i]) + ord($k[$i % strlen($k)]);
  133.  
  134.         // Try to encode it using base64
  135.         if (function_exists("base64_encode") && function_exists("base64_decode"))
  136.             return base64_encode(implode('.', $r));
  137.  
  138.         return implode('.', $r);
  139.     }
  140.  
  141.     /**
  142.      * Decode the string
  143.      * @param  string $s The string to decode
  144.      * @param  string $k The encryption key
  145.      * @return string    The decoded string
  146.      */
  147.     function _decode($s, $k)
  148.     {
  149.  
  150.         // Try to decode it using base64
  151.         if (function_exists("base64_encode") && function_exists("base64_decode"))
  152.             $s = base64_decode($s);
  153.  
  154.         $s = explode(".", $s);
  155.         $r = array();
  156.         for($i = 0; $i < count($s); $i++)
  157.             $r[$i] = chr($s[$i] - ord($k[$i % strlen($k)]));
  158.         return implode('', $r);
  159.     }
  160.  
  161.     /**
  162.      * Login
  163.      * @access public
  164.      * @param uname Username (string)
  165.      * @param pwd Password (string)
  166.      */
  167.     function login($uname, $pwd)
  168.     {
  169.         global $imSettings;
  170.  
  171.         // Check if the user exists
  172.         if (isset($imSettings['access']['users'][$uname]) && $imSettings['access']['users'][$uname]['password'] == $pwd) {
  173.             // Save the session
  174.             session_regenerate_id();
  175.             $_SESSION[$this->session_uid] = $this->_encode($imSettings['access']['users'][$uname]['id'], $imSettings['general']['salt']);
  176.             $_SESSION[$this->session_uname] = $this->_encode($uname, $imSettings['general']['salt']);
  177.             $_SESSION[$this->session_real_name] = $this->_encode($imSettings['access']['users'][$uname]['name'], $imSettings['general']['salt']);
  178.             $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT'] . $imSettings['general']['salt']);
  179.             setcookie($this->cookie_name, $this->_encode($imSettings['access']['users'][$uname]['id'], $imSettings['general']['salt']), time() + 60 * 60 * 24 * 30, "/");
  180.             return true;
  181.         }
  182.  
  183.         return false;
  184.     }
  185.  
  186.     /**
  187.      * Logout
  188.      * @access public
  189.      */
  190.     function logout() {
  191.         $_SESSION[$this->session_uname] = "";
  192.         $_SESSION[$this->session_uid] = "";
  193.         $_SESSION[$this->session_page] = "";
  194.         $_SESSION['HTTP_USER_AGENT'] = "";
  195.         setcookie($this->cookie_name, "", time() - 3600, "/");
  196.         $_COOKIE[$this->cookie_name] = "";
  197.     }
  198.  
  199.     /**
  200.      * Save the referrer page
  201.      * @access public
  202.      */
  203.     function save_page() {
  204.         global $imSettings;
  205.         $url = basename($_SERVER['PHP_SELF']);
  206.         if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']))
  207.             $url .= "?" . $_SERVER['QUERY_STRING'];
  208.         $_SESSION[$this->session_page] = $this->_encode($url, $imSettings['general']['salt']);
  209.     }
  210.  
  211.     /**
  212.      * Return to the referrer page
  213.      * @access public
  214.      */
  215.     function saved_page() {
  216.         global $imSettings;
  217.         if (isset($_SESSION[$this->session_page]) && $_SESSION[$this->session_page] != "")
  218.             return $this->_decode($_SESSION[$this->session_page], $imSettings['general']['salt']);
  219.         return false;
  220.     }
  221.  
  222.     /**
  223.      * Get an array of data about the logged user
  224.      * @access public
  225.      */
  226.     function who_is_logged() {
  227.         global $imSettings;
  228.         if (isset($_SESSION[$this->session_uname]) && $_SESSION[$this->session_uname] != "" && isset($_SESSION[$this->session_uname]))
  229.             return array(
  230.                 "username" => $this->_decode($_SESSION[$this->session_uname], $imSettings['general']['salt']),
  231.                 "uid" => $this->_decode($_SESSION[$this->session_uid], $imSettings['general']['salt']),
  232.                 "realname" => $this->_decode($_SESSION[$this->session_real_name], $imSettings['general']['salt'])
  233.             );
  234.         return false;
  235.     }
  236.  
  237.     /**
  238.      * Check if the logged user can access to a page
  239.      * @access public
  240.      * @param page The page id (string)
  241.      */
  242.     function checkAccess($page) {
  243.         global $imSettings;
  244.  
  245.         //
  246.         // The session can live only in the same browser
  247.         //
  248.  
  249.         if (!isset($_SESSION['HTTP_USER_AGENT']) || $_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'] . $imSettings['general']['salt']))
  250.             return -1;
  251.  
  252.         if (!isset($_SESSION[$this->session_uname]) || !isset($_COOKIE[$this->cookie_name]) || $_SESSION[$this->session_uname] == null || $_SESSION[$this->session_uname] == '' || $_SESSION[$this->session_uid] == null || $_SESSION[$this->session_uid] == '')
  253.             return -1; // Wrong login data
  254.  
  255.         $uid = $this->_decode($_SESSION[$this->session_uid], $imSettings['general']['salt']);
  256.         if (!@in_array($uid, $imSettings['access']['pages'][$page]) && !@in_array($uid, $imSettings['access']['admins']))
  257.             return -2; // The user cannot access to this page
  258.         return 0;
  259.     }
  260.  
  261.     /**
  262.      * Get the user's landing page
  263.      * @access public
  264.      */
  265.     function getLandingPage() {
  266.         global $imSettings;
  267.         if ($_SESSION[$this->session_uname] === null || $_SESSION[$this->session_uname] === '' || $_SESSION[$this->session_uid] === null || $_SESSION[$this->session_uid] === '')
  268.             return false;
  269.  
  270.         return $imSettings['access']['users'][$this->_decode($_SESSION[$this->session_uname], $imSettings['general']['salt'])]['page'];
  271.     }
  272. }
  273.  
  274. /**
  275.  * Contains the methods used by the search engine
  276.  * @access public
  277.  */
  278. class imSearch {
  279.  
  280.     var $scope;
  281.     var $page;
  282.     var $results_per_page;
  283.  
  284.     function __construct()
  285.     {
  286.         $this->setScope();
  287.         $this->results_per_page = 10;
  288.     }
  289.  
  290.     function imSearch()
  291.     {
  292.         $this->setScope();
  293.         $this->results_per_page = 10;
  294.     }
  295.  
  296.     /**
  297.      * Loads the pages defined in search.inc.php  to the search scope
  298.      * @access public
  299.      */
  300.     function setScope()
  301.     {
  302.         global $imSettings;
  303.         $scope = $imSettings['search']['general']['defaultScope'];
  304.  
  305.         // Logged users can search in their private pages
  306.         $pa = new imPrivateArea();
  307.         if ($user = $pa->who_is_logged()) {
  308.             foreach ($imSettings['search']['general']['extendedScope'] as $key => $value) {
  309.                 if (in_array($user['uid'], $imSettings['access']['pages'][$key]))
  310.                     $scope[] = $value;
  311.             }
  312.         }
  313.  
  314.         $this->scope = $scope;
  315.     }
  316.  
  317.     /**
  318.      * Do the pages search
  319.      * @access public
  320.      * @param queries The search query (array)
  321.      */
  322.     function searchPages($queries)
  323.     {
  324.         
  325.         global $imSettings;
  326.         $html = "";
  327.         $found_content = array();
  328.         $found_count = array();
  329.  
  330.         if (is_array($this->scope)) {
  331.             foreach ($this->scope as $filename) {
  332.                 $count = 0;
  333.                 $weight = 0;
  334.                 $file_content = @implode("\n", file($filename));
  335.  
  336.                 // Remove the page menu
  337.                 while (stristr($file_content, "<div id=\"imPgMn\"") !== false) {
  338.                     $style_start = imstripos($file_content, "<div id=\"imPgMn\"");
  339.                     $style_end = imstripos($file_content, "</div", $style_start);
  340.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  341.                     $file_content = str_replace($style, "", $file_content);
  342.                 }
  343.  
  344.                 // Remove the breadcrumbs
  345.                 while (stristr($file_content, "<div id=\"imBreadcrumb\"") !== false) {
  346.                     $style_start = imstripos($file_content, "<div id=\"imBreadcrumb\"");
  347.                     $style_end = imstripos($file_content, "</div", $style_start);
  348.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  349.                     $file_content = str_replace($style, "", $file_content);
  350.                 }
  351.  
  352.                 // Remove CSS
  353.                 while (stristr($file_content, "<style") !== false) {
  354.                     $style_start = imstripos($file_content, "<style");
  355.                     $style_end = imstripos($file_content, "</style", $style_start);
  356.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  357.                     $file_content = str_replace($style, "", $file_content);
  358.                 }
  359.  
  360.                 // Remove JS
  361.                 while (stristr($file_content, "<script") !== false) {
  362.                     $style_start = imstripos($file_content, "<script");
  363.                     $style_end = imstripos($file_content, "</script", $style_start);
  364.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  365.                     $file_content = str_replace($style, "", $file_content);
  366.                 }
  367.                 $file_title = "";
  368.  
  369.                 // Get the title of the page
  370.                 preg_match('/\<title\>([^\<]*)\<\/title\>/', $file_content, $matches);
  371.                 if (count($matches) > 1)
  372.                     $file_title = $matches[1];
  373.                 else {
  374.                     preg_match('/\<h2\>([^\<]*)\<\/h2\>/', $file_content, $matches);
  375.                     if (count($matches) > 1)
  376.                         $file_title = $matches[1];
  377.                 }
  378.  
  379.                 if ($file_title != "") {
  380.                     foreach ($queries as $query) {
  381.                         $title = imstrtolower($file_title);
  382.                         while (($title = stristr($title, $query)) !== false) {
  383.                             $weight += 5;
  384.                             $count++;
  385.                             $title = substr($title, strlen($query));
  386.                         }
  387.                     }
  388.                 }
  389.  
  390.                 // Get the keywords
  391.                 preg_match('/\<meta name\=\"keywords\" content\=\"([^\"]*)\" \/>/', $file_content, $matches);
  392.                 if (count($matches) > 1) {
  393.                     $keywords = $matches[1];
  394.                     foreach ($queries as $query) {
  395.                         $tkeywords = imstrtolower($keywords);
  396.                         while (($tkeywords = stristr($tkeywords, $query)) !== false) {
  397.                             $weight += 4;
  398.                             $count++;
  399.                             $tkeywords = substr($tkeywords, strlen($query));
  400.                         }
  401.                     }
  402.                 }
  403.  
  404.                 // Get the description
  405.                 preg_match('/\<meta name\=\"description\" content\=\"([^\"]*)\" \/>/', $file_content, $matches);
  406.                 if (count($matches) > 1) {
  407.                     $keywords = $matches[1];
  408.                     foreach ($queries as $query) {
  409.                         $tkeywords = imstrtolower($keywords);
  410.                         while (($tkeywords = stristr($tkeywords, $query)) !== false) {
  411.                             $weight += 3;
  412.                             $count++;
  413.                             $tkeywords = substr($tkeywords, strlen($query));
  414.                         }
  415.                     }
  416.                 }
  417.  
  418.                 // Remove the page title from the result
  419.                 while (stristr($file_content, "<h2") !== false) {
  420.                     $style_start = imstripos($file_content, "<h2");
  421.                     $style_end = imstripos($file_content, "</h2", $style_start);
  422.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  423.                     $file_content = str_replace($style, "", $file_content);
  424.                 }
  425.  
  426.                 $page_pos = strpos($file_content, "<div id=\"imContent\">") + strlen("<div id=\"imContent\">");
  427.                 $page_end = strpos($file_content, "<div id=\"imBtMn\">");
  428.                 if ($page_end == false)
  429.                     $page_end = strpos($file_content, "</body>");
  430.  
  431.                 $file_content = strip_tags(substr($file_content, $page_pos, $page_end-$page_pos));
  432.                 $t_file_content = imstrtolower($file_content);
  433.  
  434.                 foreach ($queries as $query) {
  435.                     $file = $t_file_content;
  436.                     while (($file = stristr($file, $query)) !== false) {
  437.                         $count++;
  438.                         $weight++;
  439.                         $file = substr($file, strlen($query));
  440.                     }
  441.                 }
  442.  
  443.                 if ($count > 0) {
  444.                     $found_count[$filename] = $count;
  445.                     $found_weight[$filename] = $weight;
  446.                     $found_content[$filename] = $file_content;
  447.                     if ($file_title == "")
  448.                         $found_title[$filename] = $filename;
  449.                     else
  450.                         $found_title[$filename] = $file_title;
  451.                 }
  452.             }
  453.         }
  454.  
  455.         if (count($found_count)) {
  456.             arsort($found_weight);
  457.             $i = 0;
  458.             foreach ($found_weight as $name => $weight) {
  459.                 $count = $found_count[$name];
  460.                 $i++;
  461.                 if (($i > $this->page*$this->results_per_page) && ($i <= ($this->page+1)*$this->results_per_page)) {
  462.                     $title = strip_tags($found_title[$name]);
  463.                     $file = $found_content[$name];
  464.                     $file = strip_tags($file);
  465.                     $ap = 0;
  466.                     $filelen = strlen($file);
  467.                     $text = "";
  468.                     for ($j=0; $j<($count > 6 ? 6 : $count); $j++) {
  469.                         $minpos = $filelen;
  470.                         foreach ($queries as $query) {
  471.                             if ($ap < $filelen && ($pos = strpos(strtoupper($file), strtoupper($query), $ap)) !== false) {
  472.                                 if ($pos < $minpos) {
  473.                                     $minpos = $pos;
  474.                                     $word = $query;
  475.                                 }
  476.                             }
  477.                         }
  478.                         $prev = explode(" ", substr($file, $ap, $minpos-$ap));
  479.                         if (count($prev) > ($ap > 0 ? 9 : 8))
  480.                             $prev = ($ap > 0 ? implode(" ", array_slice($prev, 0, 8)) : "") . " ... " . implode(" ", array_slice($prev, -8));
  481.                         else
  482.                             $prev = implode(" ", $prev);
  483.                         $text .= $prev . "<strong>" . substr($file, $minpos, strlen($word)) . "</strong>";
  484.                         $ap = $minpos + strlen($word);
  485.                     }
  486.                     $next = explode(" ", substr($file, $ap));
  487.                     if (count($next) > 9)
  488.                         $text .= implode(" ", array_slice($next, 0, 8)) . "...";
  489.                     else
  490.                         $text .= implode(" ", $next);
  491.                     $text = str_replace("|", "", $text);
  492.                     $text = str_replace("<br />", " ", $text);
  493.                     $text = str_replace("<br>", " ", $text);
  494.                     $text = str_replace("\n", " ", $text);
  495.                     $html .= "<div class=\"imSearchPageResult\"><h3><a class=\"imCssLink\" href=\"" . $name . "\">" . strip_tags($title, "<b><strong>") . "</a></h3>" . strip_tags($text, "<b><strong>") . "<div class=\"imSearchLink\"><a class=\"imCssLink\" href=\"" . $name . "\">" . $imSettings['general']['url'] . "/" . $name . "</a></div></div>\n";
  496.                 }
  497.             }
  498.             $html = preg_replace_callback('/\\s+/', create_function('$matches', 'return implode(\' \', $matches);'), $html);
  499.             $html .= "<div class=\"imSLabel\"> </div>\n";
  500.         }
  501.  
  502.         return array("content" => $html, "count" => count($found_content));
  503.     }
  504.  
  505.     function searchBlog($queries)
  506.     {
  507.         
  508.         global $imSettings;
  509.         $html = "";
  510.         $found_content = array();
  511.         $found_count = array();
  512.  
  513.         if (isset($imSettings['blog']) && is_array($imSettings['blog']['posts'])) {
  514.             foreach ($imSettings['blog']['posts'] as $key => $value) {
  515.                 $count = 0;
  516.                 $weight = 0;
  517.                 $filename = 'blog/index.php?id=' . $key;
  518.                 $file_content = $value['body'];
  519.                 // Rimuovo le briciole dal contenuto
  520.                 while (stristr($file_content, "<div id=\"imBreadcrumb\"") !== false) {
  521.                     $style_start = imstripos($file_content, "<div id=\"imBreadcrumb\"");
  522.                     $style_end = imstripos($file_content, "</div", $style_start);
  523.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  524.                     $file_content = str_replace($style, "", $file_content);
  525.                 }
  526.  
  527.                 // Rimuovo gli stili dal contenuto
  528.                 while (stristr($file_content, "<style") !== false) {
  529.                     $style_start = imstripos($file_content, "<style");
  530.                     $style_end = imstripos($file_content, "</style", $style_start);
  531.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  532.                     $file_content = str_replace($style, "", $file_content);
  533.                 }
  534.                 // Rimuovo i JS dal contenuto
  535.                 while (stristr($file_content, "<script") !== false) {
  536.                     $style_start = imstripos($file_content, "<script");
  537.                     $style_end = imstripos($file_content, "</script", $style_start);
  538.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  539.                     $file_content = str_replace($style, "", $file_content);
  540.                 }
  541.                 $file_title = "";
  542.  
  543.                 // Rimuovo il titolo dal risultato
  544.                 while (stristr($file_content, "<h2") !== false) {
  545.                     $style_start = imstripos($file_content, "<h2");
  546.                     $style_end = imstripos($file_content, "</h2", $style_start);
  547.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  548.                     $file_content = str_replace($style, "", $file_content);
  549.                 }
  550.  
  551.                 // Conto il numero di match nel titolo
  552.                 foreach ($queries as $query) {
  553.                     $t_count = preg_match_all('/' . $query . '/', imstrtolower($value['title']), $matches);
  554.                     if ($t_count !== false) {
  555.                         $weight += ($t_count * 4);
  556.                         $count += $t_count;
  557.                     }
  558.                 }
  559.  
  560.                 // Conto il numero di match nei tag
  561.                 foreach ($queries as $query) {
  562.                     if (in_array($query, $value['tag'])) {
  563.                         $count++;
  564.                         $weight += 4;
  565.                     }
  566.                 }
  567.  
  568.                 $title = "Blog >> " . $value['title'];
  569.  
  570.                 // Cerco nel contenuto
  571.                 foreach ($queries as $query) {
  572.                     $file = imstrtolower($file_content);
  573.                     while (($file = stristr($file, $query)) !== false) {
  574.                         $count++;
  575.                         $weight++;
  576.                         $file = substr($file, strlen($query));
  577.                     }
  578.                 }
  579.  
  580.                 if ($count > 0) {
  581.                     $found_count[$filename] = $count;
  582.                     $found_weight[$filename] = $weight;
  583.                     $found_content[$filename] = $file_content;
  584.                     $found_breadcrumbs[$filename] = "<div class=\"imBreadcrumb\" style=\"display: block; padding-bottom: 3px;\">" . l10n('blog_published_by') . "<strong> " . $value['author'] . " </strong>" . l10n('blog_in') . " <a href=\"blog/index.php?category=" . $value['category'] . "\" target=\"_blank\" rel=\"nofollow\">" . $value['category'] . "</a> · " . $value['timestamp'] . "</div>";
  585.                     if ($title == "")
  586.                         $found_title[$filename] = $filename;
  587.                     else
  588.                         $found_title[$filename] = $title;
  589.                 }
  590.             }
  591.         }
  592.  
  593.         if (count($found_count)) {
  594.             arsort($found_weight);
  595.             $i = 0;
  596.             foreach ($found_weight as $name => $weight) {
  597.                 $count = $found_count[$name];
  598.                 $i++;
  599.                 if (($i > $this->page*$this->results_per_page) && ($i <= ($this->page+1)*$this->results_per_page)) {
  600.                     $title = strip_tags($found_title[$name]);
  601.                     $file = $found_content[$name];
  602.                     $file = strip_tags($file);
  603.                     $ap = 0;
  604.                     $filelen = strlen($file);
  605.                     $text = "";
  606.                     for ($j=0;$j<($count > 6 ? 6 : $count);$j++) {
  607.                         $minpos = $filelen;
  608.                         foreach ($queries as $query) {
  609.                             if ($ap < $filelen && ($pos = strpos(strtoupper($file), strtoupper($query), $ap)) !== false) {
  610.                                 if ($pos < $minpos) {
  611.                                     $minpos = $pos;
  612.                                     $word = $query;
  613.                                 }
  614.                             }
  615.                         }
  616.                         $prev = explode(" ", substr($file, $ap, $minpos-$ap));
  617.                         if(count($prev) > ($ap > 0 ? 9 : 8))
  618.                             $prev = ($ap > 0 ? implode(" ", array_slice($prev, 0, 8)) : "") . " ... " . implode(" ", array_slice($prev, -8));
  619.                         else
  620.                             $prev = implode(" ", $prev);
  621.                         $text .= $prev . "<strong>" . substr($file, $minpos, strlen($word)) . "</strong> ";
  622.                         $ap = $minpos + strlen($word);
  623.                     }
  624.                     $next = explode(" ", substr($file, $ap));
  625.                     if(count($next) > 9)
  626.                         $text .= implode(" ", array_slice($next, 0, 8)) . "...";
  627.                     else
  628.                         $text .= implode(" ", $next);
  629.                     $text = str_replace("|", "", $text);
  630.                     $html .= "<div class=\"imSearchBlogResult\"><h3><a class=\"imCssLink\" href=\"" . $name . "\">" . strip_tags($title, "<b><strong>") . "</a></h3>" . strip_tags($found_breadcrumbs[$name], "<b><strong>") . "\n" . strip_tags($text, "<b><strong>") . "<div class=\"imSearchLink\"><a class=\"imCssLink\" href=\"" . $name . "\">" . $imSettings['general']['url'] . "/" . $name . "</a></div></div>\n";
  631.                 }
  632.             }
  633.             echo "  <div class=\"imSLabel\"> </div>\n";
  634.         }
  635.  
  636.         $html = preg_replace_callback('/\\s+/', create_function('$matches', 'return implode(\' \', $matches);'), $html);
  637.         return array("content" => $html, "count" => count($found_content));
  638.     }
  639.  
  640.     // Di questa funzione manca la paginazione!
  641.     function searchProducts($queries)
  642.     {
  643.         
  644.         global $imSettings;
  645.         $html = "";
  646.         $found_products = array();
  647.         $found_count = array();
  648.  
  649.         foreach ($imSettings['search']['products'] as $id => $product) {
  650.             $count = 0;
  651.             $weight = 0;
  652.             $t_title = strip_tags(imstrtolower($product['name']));
  653.             $t_description = strip_tags(imstrtolower($product['description']));
  654.  
  655.             // Conto il numero di match nel titolo
  656.             foreach ($queries as $query) {
  657.                 $t_count = preg_match_all('/' . $query . '/', $t_title, $matches);
  658.                 if ($t_count !== false) {
  659.                     $weight += ($t_count * 4);
  660.                     $count += $t_count;
  661.                 }
  662.             }
  663.  
  664.             // Conto il numero di match nella descrizione
  665.             foreach ($queries as $query) {
  666.                 $t_count = preg_match_all('/' . $query . '/', $t_description, $matches);
  667.                 if ($t_count !== false) {
  668.                     $weight++;
  669.                     $count += $t_count;
  670.                 }
  671.             }
  672.  
  673.             if ($count > 0) {
  674.                 $found_products[$id] = $product;
  675.                 $found_weight[$id] = $weight;
  676.                 $found_count[$id] = $count;
  677.             }
  678.         }
  679.  
  680.         if (count($found_count)) {
  681.             arsort($found_weight);
  682.             $i = 0;
  683.             foreach ($found_products as $id => $product) {
  684.                 $i++;
  685.                 if (($i > $this->page*$this->results_per_page) && ($i <= ($this->page+1)*$this->results_per_page)) {
  686.                     $count = $found_count[$id];
  687.                     $html .= "<div class=\"imSearchProductResult\">
  688.                     <h3 style=\"clear: both;\">" . $product['name'] . "</h3>";
  689.                     $html .= "<div class=\"imSearchProductDescription\">";
  690.                     $html .= $product['image'];
  691.                     $html .= strip_tags($product['description']) . "</div>";
  692.                     $html .= "<div class=\"imSearchProductPrice\">" . $product['price'];
  693.                     $html .= " <img src=\"cart/images/cart-add.png\" onclick=\"x5engine.cart.ui.addToCart('" . $id . "', 1);\" style=\"cursor: pointer; vertical-align: middle;\" /></div>";
  694.                     $html .= "</div>";
  695.                 }
  696.             }
  697.         }
  698.  
  699.         return array("content" => $html, "count" => count($found_products));
  700.     }
  701.  
  702.     // Di questa funzione manca la paginazione!
  703.     function searchImages($queries)
  704.     {
  705.         
  706.         global $imSettings;
  707.         $id = 0;
  708.         $html = "";
  709.         $found_images = array();
  710.         $found_count = array();
  711.  
  712.         foreach ($imSettings['search']['images'] as $image) {
  713.             $count = 0;
  714.             $weight = 0;
  715.             $t_title = strip_tags(imstrtolower($image['title']));
  716.             $t_description = strip_tags(imstrtolower($image['description']));
  717.  
  718.             // Conto il numero di match nel titolo
  719.             foreach ($queries as $query) {
  720.                 $t_count = preg_match_all('/' . $query . '/', $t_title, $matches);
  721.                 if ($t_count !== false) {
  722.                     $weight += ($t_count * 4);
  723.                     $count += $t_count;
  724.                 }
  725.             }
  726.  
  727.             // Conto il numero di match nella location
  728.             foreach ($queries as $query) {
  729.                 $t_count = preg_match_all('/' . $query . '/', imstrtolower($image['location']), $matches);
  730.                 if ($t_count !== false) {
  731.                     $weight += ($t_count * 2);
  732.                     $count += $t_count;
  733.                 }
  734.             }
  735.  
  736.             // Conto il numero di match nella descrizione
  737.             foreach ($queries as $query) {
  738.                 $t_count = preg_match_all('/' . $query . '/', $t_description, $matches);
  739.                 if ($t_count !== false) {
  740.                     $weight++;
  741.                     $count += $t_count;
  742.                 }
  743.             }
  744.  
  745.             if ($count > 0) {
  746.                 $found_images[$id] = $image;
  747.                 $found_weight[$id] = $weight;
  748.                 $found_count[$id] = $count;
  749.             }
  750.  
  751.             $id++;
  752.         }
  753.  
  754.         if (count($found_count)) {
  755.             arsort($found_weight);
  756.             $i = 0;
  757.             foreach ($found_images as $id => $image) {
  758.                 $i++;
  759.                 if (($i > $this->page*$this->results_per_page) && ($i <= ($this->page+1)*$this->results_per_page)) {
  760.                     $count = $found_count[$id];
  761.                     $html .= "<div class=\"imSearchImageResult\">";
  762.                     $html .= "<div class=\"imSearchImageResultContent\"><a href=\"" . $image['page'] . "\"><img src=\"" . $image['src'] . "\" /></a></div>";
  763.                     $html .= "<div class=\"imSearchImageResultContent\">";
  764.                     $html .= "<h3>" . $image['title'];
  765.                     if ($image['location'] != "")
  766.                         $html .= " (" . $image['location'] . ")";
  767.                     $html .= "</h3>";
  768.                     $html .= strip_tags($image['description']);
  769.                     $html .= "</div>";
  770.                     $html .= "</div>";
  771.                 }
  772.             }
  773.         }
  774.  
  775.         return array("content" => $html, "count" => count($found_images));
  776.     }
  777.  
  778.     // Di questa funzione manca la paginazione!
  779.     function searchVideos($queries)
  780.     {
  781.         
  782.         global $imSettings;
  783.         $id = 0;
  784.         $found_count = array();
  785.         $found_videos = array();
  786.         $html = "";
  787.         $month = 7776000;
  788.  
  789.         foreach ($imSettings['search']['videos'] as $video) {
  790.             $count = 0;
  791.             $weight = 0;
  792.             $t_title = strip_tags(imstrtolower($video['title']));
  793.             $t_description = strip_tags(imstrtolower($video['description']));
  794.  
  795.             // Conto il numero di match nei tag
  796.             foreach ($queries as $query) {
  797.                 $t_count = preg_match_all('/\\s*' . $query . '\\s*/', imstrtolower($video['tags']), $matches);
  798.                 if ($t_count !== false) {
  799.                     $weight += ($t_count * 10);
  800.                     $count += $t_count;
  801.                 }
  802.             }
  803.  
  804.             // I video pi├╣ recenti hanno maggiore peso in proporzione
  805.             $time = strtotime($video['date']);
  806.             $ago = strtotime("-3 months");
  807.             if ($time - $ago > 0)
  808.                 $weight += 5 * max(0, ($time - $ago)/$month);
  809.  
  810.             // Conto il numero di match nel titolo
  811.             foreach ($queries as $query) {
  812.                 $t_count = preg_match_all('/' . $query . '/', $t_title, $matches);
  813.                 if ($t_count !== false) {
  814.                     $weight += ($t_count * 4);
  815.                     $count += $t_count;
  816.                 }
  817.             }
  818.  
  819.             // Conto il numero di match nella categoria
  820.             foreach ($queries as $query) {
  821.                 $t_count = preg_match_all('/' . $query . '/', imstrtolower($video['category']), $matches);
  822.                 if ($t_count !== false) {
  823.                     $weight += ($t_count * 2);
  824.                     $count += $t_count;
  825.                 }
  826.             }
  827.  
  828.             // Conto il numero di match nella descrizione
  829.             foreach ($queries as $query) {
  830.                 $t_count = preg_match_all('/' . $query . '/', $t_description, $matches);
  831.                 if ($t_count !== false) {
  832.                     $weight++;
  833.                     $count += $t_count;
  834.                 }
  835.             }
  836.  
  837.             if ($count > 0) {
  838.                 $found_videos[$id] = $video;
  839.                 $found_weight[$id] = $weight;
  840.                 $found_count[$id] = $count;
  841.             }
  842.  
  843.             $id++;
  844.         }
  845.  
  846.         if ($found_count) {
  847.             arsort($found_weight);
  848.             foreach ($found_videos as $id => $video) {
  849.                 $i++;
  850.                 if (($i > $this->page*$this->results_per_page) && ($i <= ($this->page+1)*$this->results_per_page)) {
  851.                     $count = $found_count[$id];
  852.                     $html .= "<div class=\"imSearchVideoResult\">";
  853.                     $html .= "<div class=\"imSearchVideoResultContent\"><a href=\"" . $video['page'] . "\"><img src=\"" . $video['src'] . "\" /></a></div>";
  854.                     $html .= "<div class=\"imSearchVideoResultContent\">";
  855.                     $html .= "<h3>" . $video['title'];
  856.                     if (!$video['familyfriendly'])
  857.                         $html .= " <span style=\"color: red; text-decoration: none;\">[18+]</span>";
  858.                     $html .= "</h3>";
  859.                     $html .= strip_tags($video['description']);
  860.                     if ($video['duration'] > 0) {
  861.                         if (function_exists('date_default_timezone_set'))
  862.                             date_default_timezone_set('UTC');
  863.                         $html .= "<span class=\"imSearchVideoDuration\">" . l10n('search_duration') . ": " . date("H:i:s", $video['duration']) . "</span>";
  864.                     }
  865.                     $html .= "</div>";
  866.                     $html .= "</div>";
  867.                 }
  868.             }
  869.         }
  870.  
  871.         return array("content" => $html, "count" => count($found_videos));
  872.     }
  873.  
  874.     /**
  875.      * Start the site search
  876.      * 
  877.      * @param array  $keys The search keys as string (string)
  878.      * @param string $page Page to show (integer)
  879.      *
  880.      * @return void
  881.      */
  882.     function search($keys, $page = 0)
  883.     {
  884.         
  885.         global $imSettings;
  886.  
  887.         $html = "";
  888.         $content = "";
  889.  
  890.         //$html .= "<h2 id=\"imPgTitle\" class=\"searchPageTitle\">" . l10n('search_results') . "</h2>\n";
  891.         $html .= "<div class=\"searchPageContainer\">";
  892.         $html .= "<div class=\"imPageSearchField\"><form method=\"get\" action=\"imsearch.php\">";
  893.         $html .= "<input style=\"width: 200px; font: 8pt Tahoma; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255); padding: 3px; border: 1px solid rgb(0, 0, 0); vertical-align: middle;\" class=\"search_field\" value=\"" . $keys . "\" type=\"text\" name=\"search\" />";
  894.         $html .= "<input style=\"height: 21px; font: 8pt Tahoma; color: rgb(0, 0, 0); background-color: rgb(211, 211, 211); margin-left: 6px; padding: 3px 3px; border: 1px solid rgb(0, 0, 0); vertical-align: middle; cursor: pointer;\" type=\"submit\" value=\"" . l10n('search_search') . "\">";
  895.         $html .= "</form></div>\n";
  896.  
  897.         if ($keys == "" || $keys == null) {
  898.             $html .= "<div style=\"margin-top: 15px; text-align: center; font-weight: bold;\">" . l10n('search_empty') . "</div>\n";
  899.             echo $html;
  900.             return false;
  901.         }
  902.  
  903.         $search = trim(imstrtolower($keys));
  904.         $this->page = $page;
  905.  
  906.         if ($search != "") {
  907.             $queries = explode(" ", $search);
  908.             $blog = array("count" => 0);
  909.             $products = array("count" => 0);
  910.             $images = array("count" => 0);
  911.             $videos = array("count" => 0);
  912.  
  913.             // Pages
  914.             $pages = $this->searchPages($queries);
  915.             if ($pages['count'] > 0) {
  916.                 $content .= "<div id=\"imSearchWebPages\">" . $pages['content'] . "</div>\n";
  917.             }
  918.  
  919.             // Blog
  920.             if (isset($imSettings['blog']) && is_array($imSettings['blog']['posts']) && count($imSettings['blog']['posts']) > 0) {
  921.                 $blog = $this->searchBlog($queries);
  922.                 if ($blog['count'] > 0) {
  923.                     $content .= "<div id=\"imSearchBlog\">" . $blog['content'] . "</div>\n";
  924.                 }
  925.             }
  926.  
  927.             // Products
  928.             if (is_array($imSettings['search']['products']) && count($imSettings['search']['products']) > 0) {
  929.                 $products = $this->searchProducts($queries);
  930.                 if ($products['count'] > 0) {
  931.                     $content .= "<div id=\"imSearchProducts\">" . $products['content'] . "</div>\n";
  932.                 }
  933.             }
  934.  
  935.             // Images
  936.             if (is_array($imSettings['search']['images']) && count($imSettings['search']['images']) > 0) {
  937.                 $images = $this->searchImages($queries);
  938.                 if ($images['count'] > 0) {
  939.                     $content .= "<div id=\"imSearchImages\">" . $images['content'] . "</div>\n";
  940.                 }
  941.             }
  942.  
  943.             // Videos
  944.             if (is_array($imSettings['search']['videos']) && count($imSettings['search']['videos']) > 0) {
  945.                 $videos = $this->searchVideos($queries);
  946.                 if ($videos['count'] > 0) {
  947.                     $content .= "<div id=\"imSearchVideos\">" . $videos['content'] . "</div>\n";
  948.                 }
  949.             }
  950.  
  951.             $results_count = max($pages['count'], $blog['count'], $products['count'], $images['count'], $videos['count']);
  952.  
  953.             if ($pages['count'] == 0 && $blog['count'] == 0 && $products['count'] == 0 && $images['count'] == 0 && $videos['count'] == 0) {
  954.                 $html .= "<div style=\"text-align: center; font-weight: bold;\">" . l10n('search_empty') . "</div>\n";
  955.             } else {
  956.                 $sidebar = "<ul>\n";
  957.                 if ($pages['count'] > 0)
  958.                     $sidebar .= "\t<li><span class=\"imScMnTxt\"><a href=\"#imSearchWebPages\" onclick=\"return x5engine.imSearch.Show('#imSearchWebPages')\">" . l10n('search_pages') . " (" . $pages['count'] . ")</a></span></li>\n";
  959.                 if ($blog['count'] > 0)
  960.                     $sidebar .= "\t<li><span class=\"imScMnTxt\"><a href=\"#imSearchBlog\" onclick=\"return x5engine.imSearch.Show('#imSearchBlog')\">" . l10n('search_blog') . " (" . $blog['count'] . ")</a></span></li>\n";
  961.                 if ($products['count'] > 0)
  962.                     $sidebar .= "\t<li><span class=\"imScMnTxt\"><a href=\"#imSearchProducts\" onclick=\"return x5engine.imSearch.Show('#imSearchProducts')\">" . l10n('search_products') . " (" . $products['count'] . ")</a></span></li>\n";
  963.                 if ($images['count'] > 0)
  964.                     $sidebar .= "\t<li><span class=\"imScMnTxt\"><a href=\"#imSearchImages\" onclick=\"return x5engine.imSearch.Show('#imSearchImages')\">" . l10n('search_images') . " (" . $images['count'] . ")</a></span></li>\n";
  965.                 if ($videos['count'] > 0)
  966.                     $sidebar .= "\t<li><span class=\"imScMnTxt\"><a href=\"#imSearchVideos\" onclick=\"return x5engine.imSearch.Show('#imSearchVideos')\">" . l10n('search_videos') . " (" . $videos['count'] . ")</a></span></li>\n";
  967.                 $sidebar .= "</ul>\n";
  968.  
  969.                 $html .= "<div id=\"imSearchResults\">\n";
  970.                 if ($imSettings['search']['general']['menu_position'] == "left") {
  971.                     $html .= "\t<div id=\"imSearchSideBar\" style=\"float: left;\">" . $sidebar . "</div>\n";
  972.                     $html .= "\t<div id=\"imSearchContent\" style=\"float: right;\">" . $content . "</div>\n";
  973.                 } else {
  974.                     $html .= "\t<div id=\"imSearchContent\" style=\"float: left;\">" . $content . "</div>\n";
  975.                     $html .= "\t<div id=\"imSearchSideBar\" style=\"float: right;\">" . $sidebar . "</div>\n";
  976.                 }
  977.                 $html .= "</div>\n";
  978.             }
  979.  
  980.             // Pagination
  981.             if ($results_count > $this->results_per_page) {
  982.                 $html .= "<div style=\"text-align: center; clear: both;\">";
  983.                 // Back
  984.                 if ($page > 0) {
  985.                     $html .= "<a href=\"imsearch.php?search=" . implode("+", $queries) . "&page=" . ($page - 1) . "\"><<</a> ";
  986.                 }
  987.  
  988.                 // Central pages
  989.                 $start = max($page - 5, 0);
  990.                 $end = min($page + 10 - $start, ceil($results_count/$this->results_per_page));
  991.  
  992.                 for ($i = $start; $i < $end; $i++) {
  993.                     if ($i != $this->page)
  994.                         $html .= "<a href=\"imsearch.php?search=" . implode("+", $queries) . "&page=" . $i . "\">" . ($i + 1) . "</a> ";
  995.                     else
  996.                         $html .= ($i + 1) . " ";
  997.                 }
  998.  
  999.                 // Next
  1000.                 if ($results_count > ($page + 1) * $this->results_per_page) {
  1001.                     $html .= "<a href=\"imsearch.php?search=" . implode("+", $queries) . "&page=" . ($page + 1) . "\">>></a>";
  1002.                 }
  1003.                 $html .= "</div>";
  1004.             }
  1005.  
  1006.         } else
  1007.             $html .= "<div style=\"margin-top: 15px; text-align: center; font-weight: bold;\">" . l10n('search_empty') . "</div>\n";
  1008.  
  1009.         $html .= "</div>";
  1010.  
  1011.         echo $html;
  1012.     }
  1013. }
  1014.  
  1015.  
  1016. /**
  1017.  * Contains the methods used to style and send emails
  1018.  * @access public
  1019.  */
  1020. class ImSendEmail
  1021. {
  1022.  
  1023.     var $header;
  1024.     var $footer;
  1025.     var $bodyBackground;
  1026.     var $bodyBackgroundEven;
  1027.     var $bodyBackgroundOdd;
  1028.     var $bodyBackgroundBorder;
  1029.     var $bodySeparatorBorderColor;
  1030.     var $emailBackground;
  1031.     var $emailContentStyle;
  1032.     var $emailType = "html";
  1033.  
  1034.     function setHTMLHeader($header)
  1035.     {
  1036.         $this->header = $header;
  1037.     }
  1038.  
  1039.     function setHTMLFooter($footer)
  1040.     {
  1041.         $this->footer = $footer;
  1042.     }
  1043.  
  1044.     function setBodyBackground($val)
  1045.     {
  1046.         $this->bodyBackground = $val;
  1047.     }
  1048.  
  1049.     function setBodyBackgroundEven($val)
  1050.     {
  1051.         $this->bodyBackgroundEven = $val;
  1052.     }
  1053.  
  1054.     function setBodyBackgroundOdd($val)
  1055.     {
  1056.         $this->bodyBackgroundOdd = $val;
  1057.     }
  1058.  
  1059.     function setBodyBackgroundBorder($val)
  1060.     {
  1061.         $this->bodyBackgroundBorder = $val;
  1062.     }
  1063.  
  1064.     function setEmailBackground($val)
  1065.     {
  1066.         $this->emailBackground = $val;
  1067.     }
  1068.  
  1069.     function setEmailContentStyle($val)
  1070.     {
  1071.         $this->emailContentStyle = $val;
  1072.     }
  1073.  
  1074.     function setBodySeparatorBorderColor($val)
  1075.     {
  1076.         $this->bodySeparatorBorderColor = $val;
  1077.     }
  1078.  
  1079.     function setEmailType($type) {
  1080.         $this->emailType = $type;
  1081.     }
  1082.  
  1083.     /**
  1084.      * Apply the CSS style to the HTML code
  1085.      * @param  string $html The HTML code
  1086.      * @return string       The styled HTML code
  1087.      */
  1088.     function styleHTML($html)
  1089.     {
  1090.         $html = str_replace("[email:contentStyle]", $this->emailContentStyle, $html);
  1091.         $html = str_replace("[email:bodyBackground]", $this->bodyBackground, $html);
  1092.         $html = str_replace("[email:bodyBackgroundBorder]", $this->bodyBackgroundBorder, $html);
  1093.         $html = str_replace("[email:bodyBackgroundOdd]", $this->bodyBackgroundOdd, $html);
  1094.         $html = str_replace("[email:bodyBackgroundEven]", $this->bodyBackgroundEven, $html);
  1095.         $html = str_replace("[email:bodySeparatorBorderColor]", $this->bodySeparatorBorderColor, $html);
  1096.         $html = str_replace("[email:emailBackground]", $this->emailBackground, $html);
  1097.         return $html;
  1098.     }
  1099.  
  1100.     /**
  1101.      * Send an email
  1102.      * 
  1103.      * @param string $from        Self explanatory
  1104.      * @param string $to          Self explanatory
  1105.      * @param string $subject     Self explanatory
  1106.      * @param string $text        Self explanatory
  1107.      * @param string $html        Self explanatory
  1108.      * @param array  $attachments Self explanatory
  1109.      * 
  1110.      * @return boolean
  1111.      */
  1112.     function send($from = "", $to = "", $subject = "", $text = "", $html = "", $attachments = array())
  1113.     {
  1114.         $email = new imEMail($from, $to, $subject, "utf-8");
  1115.         $email->setText($text);
  1116.         $email->setHTML($this->header . $this->styleHTML($html) . $this->footer);
  1117.         $email->setStandardType($this->emailType);
  1118.         foreach ($attachments as $a) {
  1119.             if (isset($a['name']) && isset($a['content']) && isset($a['mime'])) {
  1120.                 $email->attachFile($a['name'], $a['content'], $a['mime']);
  1121.             }
  1122.         }
  1123.         return $email->send();
  1124.     }
  1125.  
  1126.     /**
  1127.      * Restore some special chars escaped previously in WSX5
  1128.      * 
  1129.      * @param string $str The string to be restored
  1130.      *
  1131.      * @return string
  1132.      */
  1133.     function restoreSpecialChars($str)
  1134.     {
  1135.         $str = str_replace("{1}", "'", $str);
  1136.         $str = str_replace("{2}", "\"", $str);
  1137.         $str = str_replace("{3}", "\\", $str);
  1138.         $str = str_replace("{4}", "<", $str);
  1139.         $str = str_replace("{5}", ">", $str);
  1140.         return $str;
  1141.     }
  1142.  
  1143.     /**
  1144.      * Decode the Unicode escaped chars like %u1239
  1145.      * 
  1146.      * @param string $str The string to be decoded
  1147.      *
  1148.      * @return string
  1149.      */
  1150.     function decodeUnicodeString($str)
  1151.     {
  1152.         $res = '';
  1153.  
  1154.         $i = 0;
  1155.         $max = strlen($str) - 6;
  1156.         while ($i <= $max) {
  1157.             $character = $str[$i];
  1158.             if ($character == '%' && $str[$i + 1] == 'u') {
  1159.                 $value = hexdec(substr($str, $i + 2, 4));
  1160.                 $i += 6;
  1161.  
  1162.                 if ($value < 0x0080) // 1 byte: 0xxxxxxx
  1163.                     $character = chr($value);
  1164.                 else if ($value < 0x0800) // 2 bytes: 110xxxxx 10xxxxxx
  1165.                     $character = chr((($value & 0x07c0) >> 6) | 0xc0) . chr(($value & 0x3f) | 0x80);
  1166.                 else // 3 bytes: 1110xxxx 10xxxxxx 10xxxxxx
  1167.                 $character = chr((($value & 0xf000) >> 12) | 0xe0) . chr((($value & 0x0fc0) >> 6) | 0x80) . chr(($value & 0x3f) | 0x80);
  1168.             } else
  1169.                 $i++;
  1170.  
  1171.             $res .= $character;
  1172.         }
  1173.         return $res . substr($str, $i);
  1174.     }
  1175. }
  1176.  
  1177. /**
  1178.  * Server Test Class
  1179.  * @access public
  1180.  */
  1181. class imTest {
  1182.  
  1183.     /*
  1184.      * Session check
  1185.      */
  1186.     function session_test()
  1187.     {
  1188.         
  1189.         if (!isset($_SESSION))
  1190.             return false;
  1191.         $_SESSION['imAdmin_test'] = "test_message";
  1192.         return ($_SESSION['imAdmin_test'] == "test_message");
  1193.     }
  1194.  
  1195.     /*
  1196.      * Writable files check
  1197.      */
  1198.     function writable_folder_test($dir)
  1199.     {
  1200.         if (!file_exists($dir) && $dir != "" && $dir != "./.")
  1201.             @mkdir($dir, 0777, true);
  1202.  
  1203.         $fp = @fopen(pathCombine(array($dir, "imAdmin_test_file")), "w");
  1204.         if (!$fp)
  1205.             return false;
  1206.         if (@fwrite($fp, "test") === false)
  1207.             return false;
  1208.         @fclose($fp);
  1209.         if (!@file_exists(pathCombine(array($dir, "imAdmin_test_file"))))
  1210.             return false;
  1211.         @unlink(pathCombine(array($dir, "imAdmin_test_file")));
  1212.         return true;
  1213.     }
  1214.  
  1215.     /*
  1216.      * PHP Version check
  1217.      */
  1218.     function php_version_test()
  1219.     {   
  1220.         if (!function_exists("version_compare") || version_compare(PHP_VERSION, '4.0.0') < 0)
  1221.             return false;
  1222.         return true;
  1223.     }
  1224.  
  1225.     /*
  1226.      * MySQL Connection check
  1227.      */
  1228.     function mysql_test($host, $user, $pwd, $name)
  1229.     {
  1230.         $db = new ImDb($host, $user, $pwd, $name);
  1231.         if (!$db->testConnection())
  1232.             return false;
  1233.         $db->closeConnection();
  1234.         return true;
  1235.     }
  1236.  
  1237.     /*
  1238.      * Do the test
  1239.      */
  1240.     function doTest($expected, $value, $title, $message)
  1241.     {
  1242.         if ($expected == $value)
  1243.             echo "<div class=\"imTest pass\">" . $title . "<span>PASS</span></div>";
  1244.         else
  1245.             echo "<div class=\"imTest fail\">" . $title . "<span>FAIL</span><p>" . $message . "</p></div>";
  1246.     }
  1247. }
  1248.  
  1249.  
  1250.  
  1251.  
  1252. /**
  1253.  * XML Handling class
  1254.  * @access public
  1255.  */
  1256. class imXML 
  1257. {
  1258.     var $tree = array();
  1259.     var $force_to_array = array();
  1260.     var $error = null;
  1261.     var $parser;
  1262.     var $inside = false;
  1263.  
  1264.     // PHP 5
  1265.     function __construct($encoding = 'UTF-8')
  1266.     {
  1267.         $this->setUp($encoding);
  1268.     }
  1269.  
  1270.     // PHP 4
  1271.     function imXML($encoding = 'UTF-8')
  1272.     {
  1273.         $this->setUp($encoding);   
  1274.     }
  1275.  
  1276.     function setUp($encoding = 'UTF-8')
  1277.     {
  1278.         $this->parser = xml_parser_create($encoding);
  1279.         xml_set_object($this->parser, $this); // $this was passed as reference &$this
  1280.         xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  1281.         xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
  1282.         xml_set_element_handler($this->parser, "startEl", "stopEl");
  1283.         xml_set_character_data_handler($this->parser, "charData");
  1284.         xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
  1285.     }
  1286.  
  1287.     function parse_file($file)
  1288.     {
  1289.         $fp = @fopen($file, "r");
  1290.         if (!$fp)
  1291.             return false;
  1292.         while ($data = fread($fp, 4096)) {
  1293.             if (!xml_parse($this->parser, $data, feof($fp))) {
  1294.                 return false;
  1295.             }
  1296.         }
  1297.         fclose($fp);
  1298.         return $this->tree[0]["content"];
  1299.     }
  1300.  
  1301.     function parse_string($str)
  1302.     {
  1303.         if (!xml_parse($this->parser, $str))
  1304.             return false;
  1305.         if (isset($this->tree[0]["content"]))
  1306.             return $this->tree[0]["content"];
  1307.         return false;
  1308.     }
  1309.  
  1310.     function startEl($parser, $name, $attrs)
  1311.     {
  1312.         array_unshift($this->tree, array("name" => $name));
  1313.         $this->inside = false;
  1314.     }
  1315.  
  1316.     function stopEl($parser, $name)
  1317.     {
  1318.         if ($name != $this->tree[0]["name"])
  1319.             return false;
  1320.         if (count($this->tree) > 1) {
  1321.             $elem = array_shift($this->tree);
  1322.             if (isset($this->tree[0]["content"][$elem["name"]])) {
  1323.                 if (is_array($this->tree[0]["content"][$elem["name"]]) && isset($this->tree[0]["content"][$elem["name"]][0])) {
  1324.                     array_push($this->tree[0]["content"][$elem["name"]], $elem["content"]);
  1325.                 } else {
  1326.                     $this->tree[0]["content"][$elem["name"]] = array($this->tree[0]["content"][$elem["name"]],$elem["content"]);
  1327.                 }
  1328.             } else {
  1329.                 if (in_array($elem["name"], $this->force_to_array)) {
  1330.                     $this->tree[0]["content"][$elem["name"]] = array($elem["content"]);
  1331.                 } else {
  1332.                     if (!isset($elem["content"])) $elem["content"] = "";
  1333.                     $this->tree[0]["content"][$elem["name"]] = $elem["content"];
  1334.                 }
  1335.             }
  1336.         }
  1337.         $this->inside = false;
  1338.     }
  1339.  
  1340.     function charData($parser, $data)
  1341.     {
  1342.         if (!preg_match("/\\S/", $data))
  1343.                 return false;
  1344.         if ($this->inside) {
  1345.             $this->tree[0]["content"] .= $data;
  1346.         } else {
  1347.             $this->tree[0]["content"] = $data;
  1348.         }
  1349.         $this->inside_data = true; 
  1350.     }
  1351. }
  1352.  
  1353.  
  1354. /**
  1355.  * Some useful functions
  1356.  *
  1357.  * @category X5engine
  1358.  * @package  X5engine
  1359.  * @license  Copyright by Incomedia http://incomedia.eu
  1360.  * @link     http://websitex5.com
  1361.  */
  1362.  
  1363. /**
  1364.  * Prints an error about not active JS
  1365.  *
  1366.  * @param $docType True to use the meta redirect with a complete document. False to use a javascript code.
  1367.  * 
  1368.  * @return void
  1369.  */
  1370. function imPrintJsError($docType = true)
  1371. {
  1372.     if ($docType) {
  1373.         $html = "<DOCTYPE><html><head><meta http-equiv=\"Refresh\" content=\"5;URL=" . $_SERVER['HTTP_REFERER'] . "\"></head><body>";
  1374.         $html .= l10n('form_js_error');
  1375.         $html .= "</body></html>";
  1376.     } else {
  1377.         $html = "<meta http-equiv=\"Refresh\" content=\"5;URL=" . $_SERVER['HTTP_REFERER'] . "\">";
  1378.         $html .= l10n('form_js_error');
  1379.     }
  1380.     return $html;
  1381. }
  1382.  
  1383. /**
  1384.  * Check the user's access to $page
  1385.  * 
  1386.  * @param string $page The page to check
  1387.  * 
  1388.  * @return void
  1389.  */
  1390. function imCheckAccess($page)
  1391. {
  1392.     $pa = new imPrivateArea();
  1393.     $stat = $pa->checkAccess($page);
  1394.     if ($stat !== 0) {
  1395.         $pa->save_page();
  1396.         header("Location: imlogin.php" . ($stat == -2 ? "?err=1" : ""));
  1397.         exit;
  1398.     }
  1399. }
  1400.  
  1401.  
  1402. /**
  1403.  * Shuffle an associate array
  1404.  * 
  1405.  * @param array $list The array to shuffle
  1406.  * 
  1407.  * @return array       The shuffled array
  1408.  */
  1409. function shuffleAssoc($list)
  1410. {
  1411.     if (!is_array($list))
  1412.         return $list;
  1413.     $keys = array_keys($list);
  1414.     shuffle($keys);
  1415.     $random = array();
  1416.     foreach ($keys as $key)
  1417.         $random[$key] = $list[$key];
  1418.     return $random;
  1419. }
  1420.  
  1421. /**
  1422.  * Provide a fallback for the PHP5 stripos function
  1423.  * 
  1424.  * @param string  $haystack Where to search
  1425.  * @param string  $needle   What to replace
  1426.  * @param integer $offset   Start searching from here
  1427.  * 
  1428.  * @return integer          The position of the searched string
  1429.  */
  1430. function imstripos($haystack, $needle , $offset = 0)
  1431. {
  1432.     if (function_exists('stripos')) // Is PHP5+
  1433.         return stripos($haystack, $needle, $offset);
  1434.  
  1435.     // PHP4 fallback
  1436.     return strpos(strtolower($haystack), strtolower($needle), $offset);
  1437. }
  1438.  
  1439. /**
  1440.  * Provide a localization helper
  1441.  * 
  1442.  * @param string $id      The localization key
  1443.  * @param string $default The default string
  1444.  * 
  1445.  * @return string          The localization
  1446.  */
  1447. function l10n($id, $default = "")
  1448. {
  1449.     global $l10n;
  1450.  
  1451.     if (!isset($l10n[$id]))
  1452.         return $default;
  1453.  
  1454.     return $l10n[$id];
  1455. }
  1456.  
  1457. /**
  1458.  * Combine paths
  1459.  * 
  1460.  * @param  array  $paths
  1461.  * 
  1462.  * @return string
  1463.  */
  1464. function pathCombine($paths = array())
  1465. {
  1466.     $s = array();
  1467.     foreach ($paths as $path) {
  1468.         if (strlen($path))
  1469.             $s[] = trim($path, "/\\ ");
  1470.     }
  1471.     return implode("/", $s);
  1472. }
  1473.  
  1474. /**
  1475.  * Try to convert a string to lowercase using multibyte encoding
  1476.  * 
  1477.  * @param  string $str
  1478.  * 
  1479.  * @return string
  1480.  */
  1481. function imstrtolower($str) {
  1482.     return (function_exists("mb_convert_case") ? mb_convert_case($str, MB_CASE_LOWER, "UTF-8") : strtolower($str));
  1483. }
  1484.  
  1485.  
  1486. // End of file